package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"xiao-hong-shu-stats/cache"
	"xiao-hong-shu-stats/models"
	"xiao-hong-shu-stats/pkg"
)

func Login(c *gin.Context) {
	email := c.PostForm("email")
	password := c.PostForm("password")

	if email == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	var user models.User
	err := models.DB.Where("email = ?", email).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "邮件不存在",
		})
		return
	}

	if pkg.Md5Str(password) != user.Password {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}
func Add(c *gin.Context) {
	email := c.PostForm("email")
	password := c.PostForm("password")

	if email == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	data := models.User{
		Email:    email,
		Password: password,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}

	redis_key := "user_id" + strconv.Itoa(int(data.ID))
	var user models.User
	models.DB.Where("id = ?", user.ID).Find(&user)
	jsonData, _ := json.Marshal(&user)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var user models.User
	err := models.DB.Where("id = ?", id).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 00,
		"msg":  "查询成功",
		"data": user,
	})
	return
}
func Del(c *gin.Context) {
	id := c.Query("id")
	models.DB.Delete(&models.User{}, id)
	redis_key := "user_id" + id
	cache.Rdb.Del(cache.Ctx, redis_key)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func List(c *gin.Context) {

	var user []models.User
	redis_key := "list_user"
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if errCount == "" {
		models.DB.Find(&user)
		jsonData, _ := json.Marshal(&user)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(errCount), &user)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": user,
	})
	return
}
